var app = new Vue({
    el: '#app',
    data: {
        servers: [],
        result: 0,
        type: 1,
        url: ''
    },
    created: function () {
        $.ajax({
            type: 'get',
            url: "/server",
            data: {},
            dataType: 'json',
            success: function (data) {
                Vue.set(app, "servers", data.data);
            },
            error: function (data) {
            },
        });
    },
    methods: {
        search: function () {
            var data = {
                'server': $('.server').val(),
                'status': $('.status').val(),
                'type': $('.type').val(),
                'count': $('.count').val(),
                'result': $('.result').val()
            };
            layui.refreshTable(data);
        },
        add: function () {
            layer.open({
                type: 1,
                title: '数据源配置',
                area: ['500px', '400px'],
                content: $('#dataSource')
            });
        }
    }
})

layui.define('table', function (exports) {
    let t = layui.table.render({
        elem: '#tableId',
        url: '/list',
        request: {
            pageName: 'current',
            limitName: 'size'
        },
        where: {},
        toolbar: true,
        title: '用户数据表',
        limit: 10,
        cols: [
            [{
                field: 'id',
                title: 'ID',
                width: 120,
                sort: true,
            },
                {
                    field: 'domain',
                    title: 'server',
                    width: 120,
                    sort: true
                },
                {
                    field: 'globalId',
                    title: 'globalId',
                    width: 150,
                    sort: true
                },
                {
                    field: 'branchId',
                    title: 'branchId',
                    width: 150,
                    sort: true
                },
                {
                    field: 'type',
                    title: 'type',
                    width: 80,
                    sort: true,
                    templet: function (d) {
                        if (d.type == 1) {
                            return '发起者';
                        } else if (d.type == 2) {
                            return '参与者';
                        }
                    }
                },
                {
                    field: 'status',
                    title: 'status',
                    width: 80,
                    sort: true,
                    templet: function (d) {
                        if (d.status == 1) {
                            return 'try';
                        } else if (d.status == 2) {
                            return 'confirm';
                        } else if (d.status == 3) {
                            return 'cancell';
                        }
                    }
                },
                {
                    field: 'count',
                    title: 'count',
                    width: 80
                },
                {
                    field: 'version',
                    title: 'version',
                    width: 80
                },
                {
                    field: 'result',
                    title: 'result',
                    width: 80,
                    templet: function (d) {
                        if (d.result == -1) {
                            return '失败';
                        } else if (d.result == 0) {
                            return '未知';
                        } else if (d.result == 1) {
                            return '成功';
                        }
                    }
                },
                {
                    field: 'partner',
                    title: 'method',
                    templet: function (d) {
                        return partner(d);
                    }
                },
                {
                    field: 'createTime',
                    title: 'createTime',
                    width: 190,
                    templet: function (d) {
                        return new Date(d.createTime).Format("yyyy-MM-dd hh:mm:ss.S");
                    }
                },
                {
                    field: 'updateTime',
                    title: 'updateTime',
                    width: 190,
                    templet: function (d) {
                        return new Date(d.updateTime).Format("yyyy-MM-dd hh:mm:ss.S");
                    }
                },
                {
                    field: 'ID',
                    title: '操作',
                    width: 140,
                    templet: function (d) {
                        var str = '';
                        if (d.result != 0) {
                            str = '<a lay-event="res"> <input type="checkbox" lay-skin="switch" lay-text="成功|失败" lay-filter="openid"> </a>';
                        }
                        if (d.count >= 30) {
                            str = str + '&nbsp;&nbsp;<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="try">重试</a>';
                        }
                        return str;
                    }
                }
            ]
        ],
        page: true,
        response: {
            statusCode: 200
        },
        parseData: function (res) {
            return {
                "code": res.code,
                "msg": res.mes,
                "count": res.data.total,
                "data": res.data.records
            };
        }
    });
    layui.table.on('tool(tableId)', function (d) {
        var event = d.event;
        var data = d.data;
        if (event == 'try') data.count = 0;
        if (event == 'res') data.result = app.$data.result;
        var obj = new Object()
        obj.id = data.id;
        obj.globalId = data.globalId;
        obj.branchId = data.branchId;
        obj.domain = data.domain;
        obj.status = data.status;
        obj.type = data.type;
        obj.count = data.count;
        obj.version = data.version;
        obj.result = data.result;
        $.ajax({
            type: 'post',
            url: "/update",
            data: obj,
            dataType: 'json',
            success: function (data) {
                layer.msg('成功', {
                    icon: 6
                });
                layer.closeAll();
            },
            error: function (data) {
            },
        });
    });
    exports('refreshTable', function (data) {
        t.reload({
            where: data,
            url: '/list'
        });
    });

    function partner(d) {
        var html = "";
        var partner = JSON.parse(d.partner);
        for (var i = 0; i < partner.length; i++) {
            var invocation = partner[i].cancel;
            var method = invocation.target + "." + invocation.method;
            var args = invocation.args;
            args = JSON.stringify(args);
            html += '<div style="background:#f9f1f3;margin-bottom: 2px;"><span style="color: #e40e0c;">method: ' + method + '</span><br> <span style="color: #396ca2;">args: ' + args + '</span>';
            if (i == 0) {
                var confirminvocation = partner[i].confirm;
                var confirmmethod = confirminvocation.target + "." + confirminvocation.method;
                html += '<br> <span style="color: #e40e0c;">method: ' + confirmmethod + '</span><br> <span style="color: #396ca2;">args: ' + args + '</span> </div>';
            } else {
                html += '</div>';
            }
        }
        return html;
    }
});

//(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

layui.use('form', function () {
    var form = layui.form;
    //监听提交
    form.on('submit(add_from)', function (data) {
        data.type = app.$data.type;
        $.ajax({
            type: 'post',
            url: "/import",
            data: data.field,
            dataType: 'json',
            success: function (data) {
                layer.msg('成功', {
                    icon: 6
                });
                layer.closeAll();
            },
            error: function (data) {
            },
        });
        return false;
    });
    form.on('switch(openid)', function (data) {
        var checked = this.checked;
        if (checked) {
            Vue.set(app, "result", 1);
        }
        if (!checked) {
            Vue.set(app, "result", -1);
        }
    });
    form.on('select(type)', function (data) {
        Vue.set(app, "type", data.value);
        if (data.value == 1) Vue.set(app, "url", 'jdbc:mysql://mysql2:3306/cloud?useUnicode=true&characterEncoding=UTF-8');
        if (data.value == 2) Vue.set(app, "url", '127.0.0.1');
    })
});